package com.example.myapplication1.threademo.conditiontest;

import android.util.Log;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Copyright (C), 2020, 重庆八进制有限公司
 *
 * @author: weng
 * @last-modifier: weng
 * @version: 1.0
 * @create-date: 2020/12/3 10:24
 * @last-modify-date: 2020/12/3 10:24
 * @description:测试condition
 */
public class BoundedBuffer {


    private Object[] item = new Object[100];

    private Lock lock = new ReentrantLock();
    private Condition notFull = lock.newCondition();
    private Condition notEmpty = lock.newCondition();

    private int putptr, takeptr, count;

    public void put(Object o) {
        while (true) {
            try {
                lock.lock();
                while (count == item.length) {
                    Log.e("tag", "已经满了，现在不能放了");
                    notFull.await();
                }

                item[putptr] = o;
                if (++putptr == item.length) putptr = 0;
                count++;
                notEmpty.signal();
                Log.e("tag", "放入一个");

            } catch (InterruptedException e) {

                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }


    public void take() {

        while (true) {

            try {
                lock.lock();
                while (count == 0) {
                    Log.e("tag", "空了，不仅取了");
                    notEmpty.await();

                }
                Object o = item[takeptr];
                Log.e("tag", "取出来一个o---->" + o);
                if (++takeptr == item.length) takeptr = 0;
                count--;
                notFull.signal();

            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {

                lock.unlock();
            }
        }

    }
}
